package com.ruoyi.project.utils;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.dyplsapi20170525.models.BindAxbRequest;
import com.aliyun.dyplsapi20170525.models.BindAxbResponse;
import com.aliyun.dyplsapi20170525.models.BindAxnRequest;
import com.aliyun.dyplsapi20170525.models.BindAxnResponse;
import com.aliyun.dyplsapi20170525.models.QueryRecordFileDownloadUrlResponse;
import com.aliyun.dyplsapi20170525.models.QuerySubsIdResponse;
import com.aliyun.dyplsapi20170525.models.QuerySubscriptionDetailResponse;
import com.aliyun.dyplsapi20170525.models.UnbindSubscriptionRequest;
import com.aliyun.dyplsapi20170525.models.UnbindSubscriptionResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.google.gson.Gson;
import com.ruoyi.common.constant.SystemContstant;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;

import com.ruoyi.project.content.PropertyTypeEnum;
import com.winnerlook.model.PrivacyBindBodyAx;
import com.winnerlook.model.PrivacyUnbindBody;
import com.winnerlook.model.VoiceResponseResult;
import com.winnerlook.service.VoiceSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

@Component
public class YunXinUtils {

    public final static String code = "OK";

    private static final Logger log = LoggerFactory.getLogger(YunXinUtils.class);

    private final static String SUCCESS_CODE = "000000";

    //建立一个多线程可共享的map
    private static final ConcurrentMap <Object, Object> mapLock = new ConcurrentHashMap <>();

    //云信
    @Value ("${yx.accountId}")
    private String accountId;

    @Value ("${yx.token}")
    private String token;

    //阿里云
    @Value ("${aly.AccessKeyId}")
    private String AccessKeyId;

    @Value ("${aly.AccessKeySecret}")
    private String AccessKeySecret;

    @Value ("${aly.PoolKey}")
    private String PoolKey;




    @Autowired
    private RedisUtils redisUtils;

    /**
     * 获取一天中剩余的时间（秒数）
     */
    public static Integer getDayRemainingTime (Date currentDate) {
        LocalDateTime midnight = LocalDateTime.ofInstant(currentDate.toInstant(), ZoneId.systemDefault()).plusDays(1)
                .withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime currentDateTime = LocalDateTime.ofInstant(currentDate.toInstant(), ZoneId.systemDefault());
        long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);
        return (int) seconds;
    }

    /**
     * 使用AK&SK初始化账号Client
     *
     * @param accessKeyId
     * @param accessKeySecret
     *
     * @return Client
     *
     * @throws Exception
     */
    public static com.aliyun.dyplsapi20170525.Client createClient (String accessKeyId, String accessKeySecret)
            throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dyplsapi.aliyuncs.com";
        return new com.aliyun.dyplsapi20170525.Client(config);
    }

    /**
     * 指定时间加70秒
     *
     * @param otime
     *
     * @return
     */
    public static String timePastTenSecond (String otime) {
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date dt = sdf.parse(otime);

            Calendar newTime = Calendar.getInstance();
            newTime.setTime(dt);
            newTime.add(Calendar.SECOND, 70);
            Date dt1 = newTime.getTime();
            String retval = sdf.format(dt1);
            return retval;
        } catch (Exception ex) {
            log.error("指定时间加70秒:{}", ex);
            return null;
        }
    }

    /**
     * 绑定手机号
     *
     * @param phone
     *         任务绑定的雇主电话
     * @param usertype
     *         用户类型 0-雇员 1-雇主
     * @param orderId
     *         订单id
     *
     * @return
     *
     * @throws Exception
     */
    public Map <String, Object> bindPhone (String phone, int usertype, Long orderId) throws Exception {
        Map <String, Object> result = new HashMap <>();
        // 获取所有虚拟小号
        Map <Object, Object> hmget = this.redisUtils.hmget(PropertyTypeEnum.VIRTUAL_PHONE.getText());
        for (Object key : hmget.keySet()) {
            if (mapLock.get(key) != null) {
                continue;
            }
            mapLock.put(key, 1);
            // 获取缓存中虚拟号与过期时间
            String vPhone = this.redisUtils.get(SystemContstant.DLG_BIND_PHONE + phone);
            if (StringUtils.isNotBlank(vPhone)) {
                // 分割虚拟号和过期时间
                String[] bphone = vPhone.split("-");
                // 绑定结束时间
                long jieshu = Long.valueOf(bphone[1]);//时间大
                // 当前时间
                long newtime = new Date().getTime();
                // 计算剩余时间
                long da = jieshu - newtime;
                // 已经过期则清空对应的缓存
                if (da < 0) {
                    this.redisUtils.del(SystemContstant.DLG_BIND_PHONE_TIME + bphone[0]);
                    this.redisUtils.del(SystemContstant.DLG_BIND_PHONE + phone);
                    this.redisUtils.del(SystemContstant.DLG_BIND_VIRTUAL_PHONE + bphone[0]);
                    this.alyUnbindphone(phone, bphone[0], "");
                    if (this.alybindPhone(phone, key.toString(), null, usertype, orderId)) {
                        long time = Long.valueOf(hmget.get(key) == null ? "30" : hmget.get(key).toString()).longValue();
                        long overTime = this.setBindCache(key.toString(), phone, time, usertype, orderId);
                        result.put("middleNumber", key.toString());
                        result.put("overTime", overTime);
                        mapLock.remove(key);
                        break;
                    }
                } else {
                    //	long time = Long.valueOf(hmget.get(key)==null?"30":hmget.get(key).toString()).longValue();
                    //    long overTime = setBindCache(vPhone.split("-")[0],phone,time,usertype,orderId);
                    result.put("middleNumber", vPhone.split("-")[0]);
                    result.put("overTime", bphone[1]);
                    mapLock.remove(key);
                    break;
                }
            }
            // 当前虚拟号的绑定时间 毫秒数
            String bindTime = this.redisUtils.get(SystemContstant.DLG_BIND_PHONE_TIME + key.toString());
            // 查看是否为空
            if (StringUtils.isNotBlank(bindTime)) {
                //若绑定时间大于当前时间 说明不可用
                if (Long.valueOf(bindTime).longValue() > DateUtils.getNowDate().getTime()) {
                    mapLock.remove(key);
                    continue;
                } else {
                    //获取绑定的上一个电话
                    String oldPhone = this.redisUtils.get(SystemContstant.DLG_BIND_VIRTUAL_PHONE + key);
                    if (StringUtils.isNotBlank(oldPhone)) {
                        //老号码不为空时 替换
                        //查看绑定的是否是相同号码 相同号码则延期
                        if (!oldPhone.equals(phone)) {
                            if (this.alybindPhone(phone, key.toString(), oldPhone, usertype, orderId)) {
                                long time = Long.valueOf(hmget.get(key) == null ? "30" : hmget.get(key).toString())
                                        .longValue();
                                long overTime = this.setBindCache(key.toString(), phone, time, usertype, orderId);
                                result.put("middleNumber", key.toString());
                                result.put("overTime", overTime);
                                this.redisUtils.del(SystemContstant.DLG_BIND_PHONE + oldPhone);
                                mapLock.remove(key);
                                break;
                            } else {
                                mapLock.remove(key);
                                continue;
                            }
                        } else {
                            //成功 重置时间缓存
                            long time = Long.valueOf(hmget.get(key) == null ? "30" : hmget.get(key).toString())
                                    .longValue();
                            long overTime = this.setBindCache(key.toString(), phone, time, usertype, orderId);
                            //设置返回的虚拟号 以及过期秒数
                            result.put("middleNumber", key.toString());
                            result.put("overTime", overTime);
                            mapLock.remove(key);
                            break;
                        }
                    }
                }
            }
            // 执行绑定新号码
            boolean flag = this.alybindPhone(phone, key.toString(), null, usertype, orderId);
            if (flag) {
                long time = Long.valueOf(hmget.get(key) == null ? "30" : hmget.get(key).toString()).longValue();
                long overTime = this.setBindCache(key.toString(), phone, time, usertype, orderId);
                result.put("middleNumber", key.toString());
                result.put("overTime", overTime);
                mapLock.remove(key);
                break;
            }
            mapLock.remove(key);
        }
        if (result.size() <= 0) {
            throw new RuntimeException("对方号码忙线中，请稍后重试！");
        }
        return result;
    }

    @SuppressWarnings ("unused")
    public VoiceResponseResult bindPhonexb (String phone, String phone1) throws Exception {
        PrivacyUnbindBody unbindBody = new PrivacyUnbindBody();
        unbindBody.setMiddleNumber(phone);
        unbindBody.setBindNumberA(phone1);
        VoiceResponseResult result = VoiceSender.httpsPrivacyUnbind(unbindBody, this.accountId, this.token);
        return result;
    }

    /**
     * 阿里虚拟小号绑定
     *
     * @param phone
     * @param middleNumber
     * @param oldPhone
     * @param usertype
     * @param orderId
     *
     * @return
     *
     * @throws Exception
     */
    private boolean alybindPhone (String phone, String middleNumber, String oldPhone, int usertype, Long orderId)
            throws Exception {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        com.aliyun.dyplsapi20170525.Client client = Sample.createClient(this.AccessKeyId, this.AccessKeySecret);
        BindAxnRequest bindAxnRequest = new BindAxnRequest();
        bindAxnRequest.setPoolKey(this.PoolKey);
        bindAxnRequest.setPhoneNoX(middleNumber);
        bindAxnRequest.setPhoneNoA(phone);
        bindAxnRequest.setIsRecordingEnabled(true);

        bindAxnRequest.setExpiration(timePastTenSecond(dft.format(date)));
        BindAxnResponse rs = client.bindAxn(bindAxnRequest);
        JSONObject jsonObject = JSON.parseObject(new Gson().toJson(rs));
        String message = jsonObject.getJSONObject("body").getString("message");
        String codes = jsonObject.getJSONObject("body").getString("code");


        //payOrder.setProjectOrder();
        Map <String, String> map = new HashMap <>();
        map.put("phone", phone);
        map.put("middleNumber", middleNumber);
        map.put("oldPhone", oldPhone);
        map.put("usertype", usertype + "");
        map.put("orderId", orderId + "");
        map.put("startDate", dft.format(date));
        map.put("endDate", dft.format(new Date()));

        if (code.equals(message) && code.equals(codes)) {
            String SubsId = jsonObject.getJSONObject("body").getJSONObject("secretBindDTO").getString("subsId");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date datett = simpleDateFormat.parse(bindAxnRequest.getExpiration());
            long ts = datett.getTime() / 1000;
            long newtime = new Date().getTime() / 1000;
            long cha = ts - newtime;
            this.redisUtils.set(phone + middleNumber, SubsId, cha);
            log.info("{}小号绑定成功:{}", middleNumber, phone);
            return true;
        }
        map.put("oldStartDate", dft.format(date));
        // 如果虚拟号绑定失败，则直接返回雇主电话
        this.alyUnbindphone(phone, middleNumber, oldPhone);

        map.put("oldEndDate", dft.format(new Date()));


        log.error("{}小号绑定失败:{}", middleNumber, jsonObject);
        return false;
    }


    /**
     * 绑定手机号
     *
     * @param phone
     *         任务绑定的雇主电话
     * @param oldPhone
     *         雇员手机号
     *
     * @throws Exception
     */
    public Map <String, Object> bindPhoneAxb (String phone, String oldPhone) throws Exception {
        Map <String, Object> map1 = new HashMap <>();
        map1.put("phone", phone);
        map1.put("oldPhone", oldPhone);

        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        com.aliyun.dyplsapi20170525.Client client = Sample.createClient(this.AccessKeyId, this.AccessKeySecret);
        BindAxbRequest bindAxnRequest = new BindAxbRequest();
        bindAxnRequest.setPoolKey(this.PoolKey);
        //隐私号码
        //bindAxnRequest.setPhoneNoX(middleNumber);
        //需保护的号码（雇主电话）
        bindAxnRequest.setPhoneNoA(phone);
        //拨打电话（雇员电话）
        bindAxnRequest.setPhoneNoB(oldPhone);
        bindAxnRequest.setIsRecordingEnabled(true);
        bindAxnRequest.setExpiration(timePastTenSecond(dft.format(date)));
        BindAxbResponse rs = client.bindAxb(bindAxnRequest);
        if (ObjectUtil.isEmpty(rs)) {
            return map1;
        }
        JSONObject jsonObject = JSON.parseObject(new Gson().toJson(rs));
        String message = jsonObject.getJSONObject("body").getString("message");
        String codes = jsonObject.getJSONObject("body").getString("code");
        //存入记录中

        Map <String, String> map = new HashMap <>();
        map.put("phone", phone);
        map.put("oldPhone", oldPhone);
        map.put("startDate", dft.format(date));
        map.put("endDate", dft.format(new Date()));

        //判断是否成功
        if (code.equals(message) && code.equals(codes)) {
            //请求流水
            String SubsId = jsonObject.getJSONObject("body").getJSONObject("secretBindDTO").getString("subsId");
            //隐私号码
            String secretNo = jsonObject.getJSONObject("body").getJSONObject("secretBindDTO").getString("secretNo");

            map.put("SecretNo", secretNo);
            map.put("SubsId", SubsId);

            map1.put("SecretNo", secretNo);
            map1.put("SubsId", SubsId);
        }

        return map1;
    }


    /**
     * 绑定手机号
     *
     * @param phone
     *         任务绑定的雇主电话
     * @param oldPhone
     *         雇员手机号
     *
     * @throws Exception
     */
    public Map <String, Object> bindPhoneAxb (String phone, String oldPhone,String ExpectCity) throws Exception {
        Map <String, Object> map1 = new HashMap <>();
        map1.put("phone", phone);
        map1.put("oldPhone", oldPhone);

        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        com.aliyun.dyplsapi20170525.Client client = Sample.createClient(this.AccessKeyId, this.AccessKeySecret);
        BindAxbRequest bindAxnRequest = new BindAxbRequest();
        bindAxnRequest.setPoolKey(this.PoolKey);
        //隐私号码
        //bindAxnRequest.setPhoneNoX(middleNumber);
        //需保护的号码（雇主电话）
        bindAxnRequest.setPhoneNoA(phone);
        //拨打电话（雇员电话）
        bindAxnRequest.setPhoneNoB(oldPhone);
        bindAxnRequest.setIsRecordingEnabled(true);
        bindAxnRequest.setExpectCity(ExpectCity);
        bindAxnRequest.setExpiration(timePastTenSecond(dft.format(date)));
        BindAxbResponse rs = client.bindAxb(bindAxnRequest);
        if (ObjectUtil.isEmpty(rs)) {
            return map1;
        }
        JSONObject jsonObject = JSON.parseObject(new Gson().toJson(rs));
        String message = jsonObject.getJSONObject("body").getString("message");
        String codes = jsonObject.getJSONObject("body").getString("code");

        Map <String, String> map = new HashMap <>();
        map.put("phone", phone);
        map.put("oldPhone", oldPhone);
        map.put("startDate", dft.format(date));
        map.put("endDate", dft.format(new Date()));

        //判断是否成功
        if (code.equals(message) && code.equals(codes)) {
            //请求流水
            String SubsId = jsonObject.getJSONObject("body").getJSONObject("secretBindDTO").getString("subsId");
            //隐私号码
            String secretNo = jsonObject.getJSONObject("body").getJSONObject("secretBindDTO").getString("secretNo");

            map.put("SecretNo", secretNo);
            map.put("SubsId", SubsId);

            map1.put("SecretNo", secretNo);
            map1.put("SubsId", SubsId);
        }

        return map1;
    }


    /**
     * 阿里虚拟小号绑定
     *
     * @param phone
     *         任务绑定的雇主电话
     * @param middleNumber
     *         虚拟号码
     * @param oldPhone
     *
     * @return
     *
     * @throws Exception
     */
    private boolean alyBindPhone (String phone, String middleNumber, String oldPhone) throws Exception {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        com.aliyun.dyplsapi20170525.Client client = Sample.createClient(this.AccessKeyId, this.AccessKeySecret);
        BindAxnRequest bindAxnRequest = new BindAxnRequest();
        bindAxnRequest.setPoolKey(this.PoolKey);
        bindAxnRequest.setPhoneNoX(middleNumber);
        bindAxnRequest.setPhoneNoA(phone);
        bindAxnRequest.setIsRecordingEnabled(true);
        bindAxnRequest.setExpiration(timePastTenSecond(dft.format(date)));
        BindAxnResponse rs = client.bindAxn(bindAxnRequest);
        JSONObject jsonObject = JSON.parseObject(new Gson().toJson(rs));
        String message = jsonObject.getJSONObject("body").getString("message");
        String codes = jsonObject.getJSONObject("body").getString("code");
        //存入记录中

        Map <String, String> map = new HashMap <>();
        map.put("phone", phone);
        map.put("middleNumber", middleNumber);
        map.put("oldPhone", oldPhone);
        map.put("startDate", dft.format(date));
        map.put("endDate", dft.format(new Date()));


        if (code.equals(message) && code.equals(codes)) {
            return true;
        }
        log.error("{}小号绑定失败:{}", middleNumber, jsonObject);
        return false;
    }



    private boolean bindPhone (String phone, String middleNumber, String oldPhone, int usertype, Long orderId)
            throws Exception {
        //1 构建请求参数 body
        PrivacyBindBodyAx axBindBody = new PrivacyBindBodyAx();
        //2 设置请求参数信息 （以下示例仅供参考）
        axBindBody.setMiddleNumber(middleNumber);
        axBindBody.setBindNumberA(phone);
        axBindBody.setCalleeName("顾一一");
        axBindBody.setCalleeId("330382199003070839");
        axBindBody.setMode(2);

            axBindBody.setMaxBindingTime(40);

        VoiceResponseResult result = VoiceSender.httpsPrivacyBindAx(axBindBody, this.accountId, this.token);
        /*  System.out.println(result.toString());*/
        if (SUCCESS_CODE.equals(result.getResult())) {
            //成功 返回true
            log.info("{}小号绑定成功:{}", middleNumber, phone);

            return true;
        }
        log.error("{}小号绑定失败:{}", middleNumber, result.getMessage());
        return false;
    }

    /**
     * 解绑手机号
     *
     * @param phone
     *         初始号码
     * @param middleNumber
     * @param oldPhone
     *
     * @throws Exception
     */
    @SuppressWarnings ("unused")
    public void alyUnbindphone (String phone, String middleNumber, String oldPhone) throws Exception {
        if (this.redisUtils.hasKey(phone + middleNumber)) {
            com.aliyun.dyplsapi20170525.Client client = Sample.createClient(this.AccessKeyId, this.AccessKeySecret);
            UnbindSubscriptionRequest unbindSubscriptionRequest = new UnbindSubscriptionRequest();
            // 复制代码运行请自行打印 API 的返回值
            unbindSubscriptionRequest.setPoolKey(this.PoolKey);
            unbindSubscriptionRequest.setSecretNo(middleNumber);
            String st = this.redisUtils.get(phone + middleNumber);
            if (!StringUtils.isBlank(st)) {
                unbindSubscriptionRequest.setSubsId(st);
                UnbindSubscriptionResponse unbindSubscriptionResponse = client.unbindSubscription(
                        unbindSubscriptionRequest);
                JSONObject jsonObject = JSON.parseObject(new Gson().toJson(unbindSubscriptionResponse));
                String message = jsonObject.getJSONObject("body").getString("message");
                String codes = jsonObject.getJSONObject("body").getString("code");
                if (code.equals(message) && code.equals(codes)) {
                    this.redisUtils.del(phone + middleNumber);
                }
            }
        }
    }

    /**
     * 解绑手机号
     *
     * @param phone
     * @param middleNumber
     * @param oldPhone
     *
     * @throws Exception
     */
    @SuppressWarnings ("unused")
    private void Unbindphone (String phone, String middleNumber, String oldPhone) throws Exception {

        PrivacyUnbindBody UnbindBody = new PrivacyUnbindBody();
        UnbindBody.setMiddleNumber(middleNumber);
        UnbindBody.setBindNumberA(phone);
        VoiceResponseResult resultt = VoiceSender.httpsPrivacyUnbind(UnbindBody, middleNumber, oldPhone);


    }


    /**
     * @param phone
     *         绑定手机号
     * @param time
     *         超时秒数
     *
     * @return
     *
     * @throws ParseException
     */
    private long setBindCache (String middleNumber, String phone, Long time, int usertype, Long orderId)
            throws ParseException {
        long overTime = 20000;
        int miaos = 70;//40;
        overTime = (DateUtils.getNowDate().getTime() + time * 1000);
        this.redisUtils.set(SystemContstant.DLG_BIND_VIRTUAL_PHONE + middleNumber, phone);
        this.redisUtils.set(SystemContstant.DLG_BIND_PHONE_TIME + middleNumber, overTime);
        this.redisUtils.set(SystemContstant.DLG_BIND_PHONE + phone, middleNumber + "-" + overTime);
        this.redisUtils.expire(SystemContstant.DLG_BIND_VIRTUAL_PHONE + middleNumber, miaos);
        this.redisUtils.expire(SystemContstant.DLG_BIND_PHONE_TIME + middleNumber, miaos);
        this.redisUtils.expire(SystemContstant.DLG_BIND_PHONE + phone, miaos);
        return overTime;
    }

    /**
     * 获取录音文件的下载链接
     * @return
     */
    public String queryRecordFileDownloadUrl(String callId,String callTime) throws Exception {
        com.aliyun.dyplsapi20170525.Client client = Sample.createClient(this.AccessKeyId, this.AccessKeySecret);
        com.aliyun.dyplsapi20170525.models.QueryRecordFileDownloadUrlRequest queryRecordFileDownloadUrlRequest = new com.aliyun.dyplsapi20170525.models.QueryRecordFileDownloadUrlRequest();
        queryRecordFileDownloadUrlRequest.setProductType("AXB_170");
        queryRecordFileDownloadUrlRequest.setCallId(callId);
        queryRecordFileDownloadUrlRequest.setCallTime(callTime);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        QueryRecordFileDownloadUrlResponse response = null;
        try {
            // 复制代码运行请自行打印 API 的返回值
            response = client.queryRecordFileDownloadUrlWithOptions(
                    queryRecordFileDownloadUrlRequest, runtime);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        System.out.println(JSONObject.toJSONString(response));
        if(ObjectUtil.isNotEmpty(response) && response.getBody().getCode().equals("ok")){
            return response.getBody().getDownloadUrl();
        }
        throw new RuntimeException(response.getBody().getMessage());
    }


    public static void main (String[] args) throws Exception {
        SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        com.aliyun.dyplsapi20170525.Client client = Sample.createClient("LTAI5t7hDTcUBFZD6Y8Cf7Zr",
                "ZuvvK4m4ZFg3OChqn8sODMY8Oo9jKK"
        );
       /* BindAxbRequest bindAxnRequest = new BindAxbRequest();
        bindAxnRequest.setPoolKey("FC100000172376040");
        //隐私号码
        //bindAxnRequest.setPhoneNoX(middleNumber);
        //需保护的号码（雇员电话）
        bindAxnRequest.setPhoneNoA("13267180272");
        //拨打电话（雇主电话）
        bindAxnRequest.setPhoneNoB("17857978736");
        bindAxnRequest.setIsRecordingEnabled(true);
       // bindAxnRequest.setExpectCity("深圳");
        bindAxnRequest.setExpiration(timePastTenSecond(dft.format(date)));

        System.out.println("请求参会苏："+JSONObject.toJSONString(bindAxnRequest));
        BindAxbResponse rs = client.bindAxb(bindAxnRequest);
        JSONObject jsonObject = JSON.parseObject(new Gson().toJson(rs));
        String message = jsonObject.getJSONObject("body").getString("message");
        String codes = jsonObject.getJSONObject("body").getString("code");
        //判断是否成功
        if (code.equals(message) && code.equals(codes)) {
            //请求流水
            String SubsId = jsonObject.getJSONObject("body").getJSONObject("secretBindDTO").getString("subsId");
            //隐私号码
            String SecretNo = jsonObject.getJSONObject("body").getJSONObject("secretBindDTO").getString("secretNo");
            System.out.println(SubsId);
            System.out.println("SecretNo=" + SecretNo);
        }
        System.out.println(jsonObject.toJSONString());*/
        /*String callId="416558265b125551";
        String callTime="2023-11-18 10:50:03";
        com.aliyun.dyplsapi20170525.models.QueryRecordFileDownloadUrlRequest queryRecordFileDownloadUrlRequest = new com.aliyun.dyplsapi20170525.models.QueryRecordFileDownloadUrlRequest();
        queryRecordFileDownloadUrlRequest.setProductType("AXB_170");
        queryRecordFileDownloadUrlRequest.setCallId(callId);
        queryRecordFileDownloadUrlRequest.setCallTime(callTime);
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        QueryRecordFileDownloadUrlResponse response = null;
        try {
            // 复制代码运行请自行打印 API 的返回值
            response = client.queryRecordFileDownloadUrlWithOptions(
                    queryRecordFileDownloadUrlRequest, runtime);
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }
        if(ObjectUtil.isNotEmpty(response) && response.getBody().getCode().equals("ok")){
            System.out.println(response.getBody().getDownloadUrl());
        }else {
            System.out.println(response.getBody().getMessage());
        }
        System.out.println(JSONObject.toJSONString(response));

*/

        /*com.aliyun.dyplsapi20170525.models.QuerySubsIdRequest querySubsIdRequest = new com.aliyun.dyplsapi20170525.models.QuerySubsIdRequest();
        querySubsIdRequest.setPoolKey("FC100000172376040");
        querySubsIdRequest.setPhoneNoX("16763437084");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            QuerySubsIdResponse querySubsIdResponse = client.querySubsIdWithOptions(querySubsIdRequest, runtime);
            System.out.println(JSONObject.toJSONString(querySubsIdResponse));
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }*/


        com.aliyun.dyplsapi20170525.models.QuerySubscriptionDetailRequest querySubscriptionDetailRequest = new com.aliyun.dyplsapi20170525.models.QuerySubscriptionDetailRequest();
        querySubscriptionDetailRequest.setPoolKey("FC100000172376040");
        querySubscriptionDetailRequest.setProductType("AXB_170");
        querySubscriptionDetailRequest.setSubsId("1000142420699634");
        querySubscriptionDetailRequest.setPhoneNoX("16763436943");
        com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();
        try {
            // 复制代码运行请自行打印 API 的返回值
            QuerySubscriptionDetailResponse querySubscriptionDetailResponse = client.querySubscriptionDetailWithOptions(
                    querySubscriptionDetailRequest, runtime);
            System.out.println(JSONObject.toJSONString(querySubscriptionDetailResponse));
        } catch (TeaException error) {
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        } catch (Exception _error) {
            TeaException error = new TeaException(_error.getMessage(), _error);
            // 如有需要，请打印 error
            com.aliyun.teautil.Common.assertAsString(error.message);
        }

    }


}
